package main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 返回mysql数据
 *
 * @author hxl carlin
 */
public class ConMysql {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConMysql.class);

    public Connection getCon() throws SQLException {
        Properties properties = new Properties();
        Connection connect = null;

        try (InputStream ins = new FileInputStream("/mysql/agent/conf/db.properties")) {
            properties.load(ins);
            String url = properties.getProperty("jdbc.url");
            String user = properties.getProperty("jdbc.username");
            String password = properties.getProperty("jdbc.password");
            String driver = properties.getProperty("jdbc.driver");

            // 加载MYSQL JDBC驱动程序
            Class.forName(driver);
            LOGGER.info("Success loading Mysql Driver!");

            connect = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            LOGGER.info("ERROR loading Mysql Driver!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return connect;

    }

    /**
     * @param connect
     * @param sql
     * @return
     */
    public Map<String, String> getMysqlData(Connection connect, String sql) {

        Map<String, String> mysqlData = null;
        try (Statement stmt = connect.createStatement()) {
            ResultSet rs = stmt.executeQuery(sql);
            mysqlData = new HashMap<String, String>();
            while (rs.next()) {
                mysqlData.put(rs.getString("VARIABLE_NAME"),
                        rs.getString("VARIABLE_VALUE"));
            }

        } catch (SQLException e) {

            e.printStackTrace();
        }
        return mysqlData;

    }


}
